$(function () {
    // 获取文章id
    let id = new URLSearchParams(location.search).get('id')

    //定义获取评论的函数
    function getComments() {
        $.ajax({
            type: 'GET',
            url: 'http://localhost:8888/api/articles/' + id + '/comments',
            success: function (res) {
                if (res.status !== 0) return console.log(res.message);     
                for (var k in res.data) {
                    var date = new Date(res.data[k].cdate)
                    var y = date.getFullYear()
                    var m = (date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)
                    var d = date.getDay() > 10 ? date.getDay() : '0' + date.getDay()
                    res.data[k].cdate = y + '-' + m + '-' + d
                }
                var htmlStr = template('tpl', res)
                $('.commentArea').html(htmlStr)
            }
        })
    }
    //获取评论列表的函数
    getComments()

    //提交评论的函数
    $('#submit').on('click', function (e) {
        e.preventDefault();
        var content = $('.form textarea').val()
        $.ajax({
            type: 'post',
            url: 'http://localhost:8888/api/articles/' + id + '/comments',
            data: {
                uname: '王五',
                content
            },
            success: function (res) {
                if (res.status !== 0) return console.log(res.message);
                getComments();
            }
        })
    })
})